package com.rocksea.app.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import com.rocksea.app.R;
import com.rocksea.app.entry.CheckVersion;
import com.rocksea.app.event.UpDateVersionEvent;
import com.rocksea.app.fragment.ExpandableListFragment;
import com.rocksea.app.fragment.FileCenterFragment;
import com.rocksea.app.fragment.UserFragment;
import com.rocksea.app.http.UpDateTask;
import com.rocksea.app.utils.UiUtils;
import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener
{
    @InjectView(R.id.navigation)
    BottomNavigationView navigation;
    private UserFragment mUserFragment;
    private ExpandableListFragment mHistoryListFragment;
    private FileCenterFragment mFileCenterFragment;
    private Fragment[] mFragments = new Fragment[3];
    private int lastShowFragment = 0;
    private boolean isCanFinish = false;                    //记录再按一次退出的状态

    private final static String UPDATE_TIME = "UPDATE_TIME";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        transparencyBar(this);
        //BottomNavigationViewHelper.disableShiftMode(navigation);
        initFragment();
        navigation.setOnNavigationItemSelectedListener(this);
        navigation.getMenu().getItem(0).setChecked(true);
    }
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.navigation_red:
                if (mFileCenterFragment==null)
                {
                    mFileCenterFragment = FileCenterFragment.newInstance();
                    mFragments[0] = mFileCenterFragment;
                }
                if (lastShowFragment!=0)
                {
                    switchFragment(lastShowFragment,0);
                }
                return true;

            case R.id.navigation_dashboard:

                if (mHistoryListFragment==null)
                {
                    mHistoryListFragment = ExpandableListFragment.newInstance();
                    mFragments[1] = mHistoryListFragment;
                }
                if (lastShowFragment!=1)
                {
                    switchFragment(lastShowFragment,1);
                }
                return true;
            case R.id.navigation_notifications:
                if (mUserFragment==null)
                {
                    mUserFragment = UserFragment.newInstance();
                    mFragments[2] = mUserFragment;
                }
                if (lastShowFragment!=2)
                {
                    switchFragment(lastShowFragment,2);
                }
                return true;


        }
        return false;
    }

    private void initFragment(){
        mFileCenterFragment = FileCenterFragment.newInstance();
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.content, mFileCenterFragment)
                .show(mFileCenterFragment)
                .commit();
        mFragments[0] = mFileCenterFragment;
        mFragments[1] = mHistoryListFragment;
        mFragments[2] = mUserFragment;
    }
    /**
     * 切换Fragment
     *
     * @param lastIndex 上个显示Fragment的索引
     * @param index     需要显示的Fragment的索引
     */
    public void switchFragment(int lastIndex, int index)
    {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.hide(mFragments[lastIndex]);
        if (!mFragments[index].isAdded())
        {
            transaction.add(R.id.content, mFragments[index]);
        }
        transaction.show(mFragments[index]).commitAllowingStateLoss();
        lastShowFragment = index;
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
    }

    @TargetApi(19)
    public static void transparencyBar(Activity activity)
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        {
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            //window.setNavigationBarColor(Color.TRANSPARENT);
        }
        else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            Window window = activity.getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @Override
    public void onBackPressed()
    {
        //super.onBackPressed();
        //moveTaskToBack(false);
        if (!isCanFinish)
        {
            UiUtils.showToast("再按一次退出");
            isCanFinish = true;
            new Handler().postDelayed(new Runnable()
            {
                @Override
                public void run()
                {
                    isCanFinish = false;
                }
            }, 2*1000);
        }
        else
        {
            isCanFinish = false;
            super.onBackPressed();
        }
    }

    /*@Override
    public void onCheckVersionCallBack(final CheckVersion.DataBean.ListBean checkInfo)
    {
        String versionName = null;
        try
        {
            versionName = getPackageManager().getPackageInfo(getPackageName(),0).versionName;
        }
        catch (PackageManager.NameNotFoundException e)
        {
            e.printStackTrace();
        }
        if (versionName == null|| checkInfo == null || versionName.equals(checkInfo.getVersionName()))
            return;
        EventBus.getDefault().postSticky(new UpDateVersionEvent());
    }*/
    /*private static class BottomNavigationViewHelper
    {
        private static void disableShiftMode(BottomNavigationView view) {
            BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
            try {
                Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
                shiftingMode.setAccessible(true);
                shiftingMode.setBoolean(menuView, false);
                shiftingMode.setAccessible(false);
                for (int i = 0; i < menuView.getChildCount(); i++) {
                    BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
                    //noinspection RestrictedApi
                    item.setShiftingMode(false);
                    // set once again checked value, so view will be updated
                    //noinspection RestrictedApi
                    item.setChecked(item.getItemData().isChecked());
                }
            } catch (NoSuchFieldException e) {
                Log.e("BNVHelper", "Unable to get shift mode field", e);
            } catch (IllegalAccessException e) {
                Log.e("BNVHelper", "Unable to change value of shift mode", e);
            }
        }
    }*/
}
